/**
 * @author Mars
 */
var username;

$(function(){
	$.ziGET('getMyName', '', function(r){
		username = r;
		chat.login(username, 0);
	});
	chat.init();
	//$('#user-list1').jScrollPane();
});


var chat = {
	
	// data holds variables for use in the class:
	
	data : {
		cache		: false,
		lastID 		: 0,
		noActivity	: 0,
		currentH	: 0,
		currentC	: 0,
		columnH		: 384,
		lastUserID  : 0
	},
	
	// Init binds event listeners and sets up timers:
	
	init : function(){
		
		

		// We use the working variable to prevent
		// multiple form submissions:
		
		var working = false;
		
		chat.data.jspAPI = $('#chat-log').jScrollPane().data('jsp');
		chat.getUsers(chat.getNewUsers());
		
		$('#test').click(function(){
			$('#chat-column1').children().remove();
			$('#chat-column2').children().remove();
			chat.data.cache = false;
			chat.data.currentC = 0;
			chat.data.currentH = 0;
			(function getChatsTimeoutFunction(){
				if(!chat.data.cache)
					chat.getChats(getChatsTimeoutFunction);
			})();
		});

		//select all the a tag with name equal to modal
		$('a[name=modal]').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
		
			//Get the A tag
			var id = $(this).attr('href');
	
	
		
	
			//Get the window height and width
			var winH = $(window).height();
			var winW = $(window).width();
              
			//Set the popup window to center
			$(id).css('top',  winH/2-$(id).height()/2);
			$(id).css('left', winW/2-$(id).width()/2);
	
			
			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({
				'width':winW,
				'height':winH
			});
			
			//transition effect
			$('#mask').fadeTo("slow",0.5);	
	
			//transition effect
			$(id).fadeIn(2000); 
	
		});
		
		$('a[href=#chat-log]').click(function(e){
			chat.getChatsLog();
		});
		
		
		
		//if close button is clicked
		$('.window .close').click(function (e) {
			//Cancel the link behavior
			e.preventDefault();
		
			$('#mask').hide();
			$('.window').hide();
		});
		
		//reposition elements when resize
		$(window).resize(function(){
			var id = $('div.window');
			var winH = $(window).height();
			var winW = $(window).width();
			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({
				'width':winW,
				'height':winH
			});
			//Set the popup window to center
			$(id).css('top',  winH/2-$(id).height()/2);
			$(id).css('left', winW/2-$(id).width()/2);
		});
		
		
		// Submitting a new chat entry:
		
		$('#send-message-area').submit(function(){
			var text = $('#sendie').val();
				
			if(text.length == 0){
				return false;
			}
			if(chat.data.gravatar == 0)
			{
				chat.data.gravatar = './img/noavatar_small.gif';	
			}
				
			if(working) return false;
			working = true;
				
			// Assigning a temporary ID to the chat:
			var tempID = 't'+Math.round(Math.random()*1000000),
		
			
			params = {
				id			: tempID,
				author		: username,
				gravatar	: chat.data.gravatar,
				text		: text.replace(/</g,'&lt;').replace(/>/g,'&gt;'),
				mark		: 0
			};
	
			//add the chat to the screen immediately
				
			chat.addChatLine($.extend({},params));
			$.ziPOST('submitChat',$(this).serialize(),function(r){
				working = false;
					
				$('#sendie').val('');
				$('#chat-'+tempID).remove();
				params['id'] = r.insertID;
				chat.addChatLine($.extend({},params));
				//chat.addChatLine($.extend({},params));
			});
			return false;
		});
		
		$('#sendie').bind("keyup keydown", function(e){
			if(e.ctrlKey && e.keyCode==13){
				$('#send-message-area').submit();
			}
		});
		
		(function getChatsTimeoutFunction(){
			if(!chat.data.cache)
				chat.getChats(getChatsTimeoutFunction);
		})();
		
	},
	
	getNewUsers : function(){
		chat.getUsers(chat.getNewUsers);
	},
	
	getChats : function(callback){
		$.ziGET('getChats',{
			lastID: chat.data.lastID
		},function(r){
			
			for(var i=0;i<r.chats.length;i++){
				chat.addChatLine(r.chats[i]);
			}
			
		
			setTimeout(callback,1000);
		});
	},
	
	addChatLine : function(params){
		
		// All times are displayed in the user's timezone
		
		var d = new Date();
		if(params.time) {
			
			// PHP returns the time in UTC (GMT). We use it to feed the date
			// object and later output it in the user's timezone. JavaScript
			// internally converts it for us.
			
			d.setUTCHours(params.time.hours,params.time.minutes);
		}
		
		params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
		(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
		
		var markup = chat.render('chatLine',params);
		var exists = $('#chat-'+params.id);
		
		
		if(!exists.length){
			switch(chat.data.currentC){
				//working in the first column
				case 0:
					var h = 0;
					$('#chat-column1').append(markup);
					if(params.id.toString().charAt(0) != 't'){
						h = $('#chat-'+params.id).height()+10;
						chat.data.currentH+=h;
					}
					if(chat.data.currentH>=chat.data.columnH){
						//if exceeded, get into the second column
						$('#chat-'+params.id).remove();
						$('#chat-column2').append(markup);
						chat.data.currentC = 1;
						chat.data.currentH = h;
					}
					if(params.id.toString().charAt(0) != 't'){
						$likeElements = $('.chat .like');
						$dislikeElements = $('.chat .dislike');
						$target = $('#chat-'+params.id);
						$target.find($likeElements).bind('click', function() {
							$.ziPOST('markAChat',{like: 1, id: params.id},function(r){
								$('#chat-'+params.id).find($('span[class=markValue]')).html(r['newMark']);
							});
						});
						$target.find($dislikeElements).bind('click', function() {
							$.ziPOST('markAChat',{like: 0, id: params.id},function(r){
								$('#chat-'+params.id).find($('span[class=markValue]')).html(r['newMark']);
							});
						});
					}

					break;
				//working in the second
				case 1:
					$('#chat-column2').append(markup);
					if(params.id.toString().charAt(0) != 't')
						chat.data.currentH+=($('#chat-'+params.id).height()+10);
					if(chat.data.currentH>=chat.data.columnH){
						//if exceeded, get into the second column
						$('#chat-'+params.id).remove();
						//stop pending after all full
						chat.data.currentC = 2;
						chat.data.currentH = 0;
						chat.data.cache = true;
						chat.data.lastID = params.id-1;
					}
					if(params.id.toString().charAt(0) != 't'){
						$likeElements = $('.chat .like');
						$dislikeElements = $('.chat .dislike');
						$('#chat-'+params.id).find($likeElements).bind('click', function() {
							$.ziPOST('markAChat',{like: 1, id: params.id},function(r){
								$('#chat-'+params.id).find($('span[class=markValue]')).html(r['newMark']);
							});
						});
						$('#chat-'+params.id).find($dislikeElements).bind('click', function() {
							$.ziPOST('markAChat',{like: 0, id: params.id},function(r){
								$('#chat-'+params.id).find($('span[class=markValue]')).html(r['newMark']);
							});
						});
					}
					break;
				//all columns full
				case 2:
					//do nothing
					break;
				default:
					alert("error");
			}
			$('#chat-'+params.id).hide().fadeIn();
		}
	},
	
	addChatLog : function(params){
		
		var d = new Date();
		if(params.time) {
			
			// PHP returns the time in UTC (GMT). We use it to feed the date
			// object and later output it in the user's timezone. JavaScript
			// internally converts it for us.
			
			d.setUTCHours(params.time.hours,params.time.minutes);
		}
		
		params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
		(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
		
		var markup = chat.render('chatLogLine',params);
		chat.data.jspAPI.getContentPane().append(markup);
		
	//$('#chat-log').append(markup);
	},
	
	getChatsLog : function(){
		$.ziGET('getChatsLog',null,function(r){
			
			for(var i=0;i<r.chats.length;i++){
				chat.addChatLog(r.chats[i]);
			}
			
			chat.data.jspAPI.reinitialise();
		});
		
	},
		
	render : function(template,params){
		var arr = [];
		if(params.gravatar == 0 || params.gravatar == '')
		{
			params.gravatar = './img/noavatar_small.gif';
		}
		switch(template){
			case 'loginTopBar':
				arr = [
				'<span><img src="',params.gravatar,'" width="30" height="30" />',
				'<div id="topbar-user-text"><span class="name">',params.author,
				'</span><a href="#" class="logoutButton"> Logout</a></div></span>'];
				break;
			
			case 'chatLine':
				arr = [
				'<div id="chat-',params.id,'" class="chat">',
				'<div class="avatar"><img src="',params.gravatar,'"/></div>',
				'<div class="contentBox shadow2 roundedS"><div class="triL"></div><span class="author">',params.author,' </span> posted at <span class="time">',params.time,'</span>',
				'<hr><span class="text">',params.text,'</span>',
				'</span><br />',
				'<div class="mark"><span class="markValue">',params.mark,'</span> <button class="like"></button><button class="dislike"></button></div>',
				'</div></div>'];
				break;
			
			case 'chatLogLine':
				arr = [
				'<div id="chatLog-',params.id,'" class="chatLog rounded">',
				params.author, '<span class="author">',params.text,
				'</span><span class="time">',params.time,'</span></div>'];
				break;
			
			case 'user':
				if( params.name == username ) {
					arr = [
					'<div class="userlist_user rounded" is_current="yes" title="', params.name, 
					'" > <img class="user-icon rounded" src="', params.gravatar, 
					'"onload="this.style.visibility=\'visible\'" /></div>'
					];
				} else {
					arr = [
					'<div class="userlist_user rounded" title="', params.name, 
					'" > <img class="user-icon rounded" src="', params.gravatar, 
					'"onload="this.style.visibility=\'visible\'" /></div>'
					];
				}
				break;
		}
		
		// A single array join is faster than
		// multiple concatenations
		
		return arr.join('');
		
	},
	
	
	displayLog : function(){
		var elem = $('<div>',{
			id		: 'chatErrorMessage',
			html	: msg
		});

	},
	
	// show the user infromation
	
	login : function(name,gravatar){
		chat.data.author = name;
		chat.data.gravatar = gravatar;
		$('#topbar-user').html(chat.render('loginTopBar',chat.data));
		$("#topbar-user a").click( function() {
			$.ziGET('logout', 0, function(r){
				alert('You have logout!');
				window.location.reload();
			});
		});
		
	},
	
	// The render method generates the HTML markup 
	// that is needed by the other methods:

	
	// The addChatLine method ads a chat entry to the page
	

	
	// This method requests the latest chats
	// (since lastID), and adds them to the page.
	

	
	// Requesting a list with all the users.
	
	getUsers : function(callback){
		$.ziGET('getUsers',{
			lastID: chat.data.lastID
		},function(r){
			var users = [];
			var total = r.users.length;
			for(var i=0; i< total;i++){
				if(r.users[i]){
					users.push(chat.render('user',r.users[i]));
				}
			}
			var message = '';
			if(total < 1){
				message = 'No one is online';
			}
			users.push('<p class="count">'+message+'</p>');
			$('#user-list1').html(users.join(''));
			setTimeout(callback,10000);		
		});
	},
	
	// This method displays an error message on the top of the page:
	
	displayError : function(msg){
		var elem = $('<div>',{
			id		: 'chatErrorMessage',
			html	: msg
		});
		
		elem.click(function(){
			$(this).fadeOut(function(){
				$(this).remove();
			});
		});
		
		setTimeout(function(){
			elem.click();
		},5000);
		
		elem.hide().appendTo('body').slideDown();
	}
};


// Custom GET & POST wrappers:

$.ziPOST = function(action,data,callback){
	$.post('ajax.php?action='+action,data,callback,'json');
}

$.ziGET = function(action,data,callback){
	$.get('ajax.php?action='+action,data,callback,'json');
}